<?php

namespace backend\modules\home\controllers;

use Yii;
use backend\modules\home\models\Category;
use backend\modules\home\models\CategorySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * CategoryController implements the CRUD actions for Category model.
 */
class CategoryController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Category models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new CategorySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        // $list = $this->getAllCate();
        // $list = $this->getTree($list, 0);
        // echo "<pre>";
        // print_r($list);exit;
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Category model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Category model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Category();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        $list = $this->getAllCate();
        $list = $this->tree(0,$list);

        return $this->render('create', [
            'model' => $model,
            'list'  => $list,
        ]);
    }

    public function getAllCate(){
        return Category::find()
            ->select('id,cid,title,code,sort')
            ->orderBy('sort desc')
            ->asArray()
            ->all();
    }

    public function tree($cid = 0,$arr,$spac = '==',$level = 0)
    {
        $result = array();
        foreach($arr as $v){
            if($v['cid']==$cid)
            {
                $v['level'] = $level;
                $v['spac'] = str_repeat($spac,$v['level']);
                $result[] = $v;
                $result = array_merge($result,$this->tree($v['id'],$arr,$spac,$level + 1));
            }
        }
        return $result;

    }

    public function getTree($data, $cid)
    {
        $tree = [];
        foreach($data as $k => $v)
        {
            if($v['cid'] == $cid)
            {        //父亲找到儿子
                $v['options'] = $this->getTree($data, $v['id']);
                $tree[] = $v;
                //unset($data[$k]);
            }
        }
        return $tree;
    }

    /**
     * Updates an existing Category model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        $list = $this->getAllCate();
        $list = $this->tree(0,$list);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
            'list'  => $list,
        ]);
    }

    /**
     * Deletes an existing Category model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Category model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Category the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Category::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
